package com.pan.concurrency.thread;

import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * <p>
 *  代码同步块：使关键性执行代码由并行编程串行
 *
 *  1. run 代码段中有多行，相关的关键性代码 也不是tickets-- 所以不是原子性的。
 *  这段代码在多线程出现问题了。卖出了相同的两张票。
 *
 *  2. 在Synchronized3Thread中改造
 * </p>
 *
 * @author kaiji
 * @since 2020/1/25 11:32
 */
public class Synchronized2Thread {

    // private static int tickets = 100;

    public static void main(String[] args) {
        Sale2 saleZh = new Sale2("张三");
        Sale2 saleLi = new Sale2("李四");
        // for (int i = 0; i < 10; i++) {
            Thread zhSan = new Thread(saleZh);
            Thread liSi = new Thread(saleLi);

            zhSan.start();
            liSi.start();
        // }


    }



}

class Sale2 implements Runnable {
    private String username;
    private static int tickets = 100;

    Sale2(String username) {
        this.username = username;
    }
    @Override
    public void run() {

        while (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {}
            int tmp = tickets;
            tickets = tmp - 1;
            System.out.println(username + "卖票成功，当前票号为：" + tmp);
        }

    }
}



